#!/usr/bin/env bash
set -o nounset \
    -o verbose \
    -o xtrace
#define ZOOKEEPER_SERVER_ID
export ZOOKEEPER_SERVER_ID=`expr ${HOSTNAME#*-} + 1`

#define KAFKA_ADVERTISED_LISTENERS
export ZOOKEEPER_CLIENT_PORT=${ZOOKEEPER_CLIENT_PORT-2181}

# set default_java_mem_opts
case ${MEMORY_SIZE:-small} in
    "micro")
       export default_java_mem_opts="-Xms90m -Xmx90m -Xss512k  -XX:MaxDirectMemorySize=12M"
       echo "Optimizing java process for 128M Memory...." >&2
       ;;
    "small")
       export default_java_mem_opts="-Xms180m -Xmx180m -Xss512k -XX:MaxDirectMemorySize=24M "
       echo "Optimizing java process for 256M Memory...." >&2
       ;;
    "medium")
       export default_java_mem_opts="-Xms360m -Xmx360m -Xss512k -XX:MaxDirectMemorySize=48M"
       echo "Optimizing java process for 512M Memory...." >&2
       ;;
    "large")
       export default_java_mem_opts="-Xms720m -Xmx720m -Xss512k -XX:MaxDirectMemorySize=96M "
       echo "Optimizing java process for 1G Memory...." >&2
       ;;
    "2xlarge")
       export default_java_mem_opts="-Xms1420m -Xmx1420m -Xss512k -XX:MaxDirectMemorySize=192M"
       echo "Optimizing java process for 2G Memory...." >&2
       ;;
    "4xlarge")
       export default_java_mem_opts="-Xms2840m -Xmx2840m -Xss512k -XX:MaxDirectMemorySize=384M "
       echo "Optimizing java process for 4G Memory...." >&2
       ;;
    "8xlarge")
       export default_java_mem_opts="-Xms5680m -Xmx5680m -Xss512k -XX:MaxDirectMemorySize=768M"
       echo "Optimizing java process for 8G Memory...." >&2
       ;;
    16xlarge|32xlarge|64xlarge)
       export default_java_mem_opts="-Xms8G -Xmx8G -Xss512k -XX:MaxDirectMemorySize=1536M"
       echo "Optimizing java process for biger Memory...." >&2
       ;;
    *)
       export default_java_mem_opts="-Xms128m -Xmx128m -Xss512k -XX:MaxDirectMemorySize=24M"
       echo "Optimizing java process for 256M Memory...." >&2
       ;;
esac



if [[ "${JAVA_OPTS-}" == *-Xmx* ]]; then
  export JAVA_TOOL_OPTIONS=${JAVA_TOOL_OPTIONS:-"-Dfile.encoding=UTF-8"}
else
  default_java_opts="${default_java_mem_opts} -Dfile.encoding=UTF-8"
  export JAVA_OPTS="${default_java_opts} ${JAVA_OPTS-}"
fi
#define KAFKA_HEAP_OPTS
export KAFKA_HEAP_OPTS=${JAVA_OPTS-}

#detect ZooKeeper cluster 
# if [ ! -n ${SERVICE_NAME-} ]; then
#    echo "there is no zookeeper init... exiting"
#    exit 1
# else    
#    zks=$(nslookup ${SERVICE_NAME-} | grep Address | sed '1d' | awk '{print $2":2888:3888"}')
#    export ZOOKEEPER_SERVERS=$(echo $zks | tr ' ' ';')
# fi

#detect zookeeper cluster node by hostname
[[ ${PAUSE-} ]] && sleep $PAUSE
if [ ${SERVICE_POD_NUM-} -gt 1 ]; then
   declare -a hosts
    for i in $(seq ${SERVICE_POD_NUM-})
      do
        hosts[$i-1]=${HOSTNAME%-*}-`expr $i - 1`.${HOSTNAME%-*}:2888:3888
      done
    echo "zookeeper cluster nodes are ${hosts[@]}"
    export ZOOKEEPER_SERVERS=$(echo ${hosts[@]} | tr ' ' ';')
fi